#!/bin/bash
ROOT="/data/publish"
FILE="/data/publish/gatewayui"
VOLUME="/data/publish/volume/gatewayui"
NAME="gateway-ui-front"
PUSHREMOTE="nexus.niceloo.com:8084"
echo '开始部署'
if [ ! -d $ROOT ];then
   mkdir -p $ROOT
fi
cd $ROOT

if [ -d $FILE ]
then
    echo '文件夹存在'
    # shellcheck disable=SC2164
    cd $FILE
    echo '1.正在停止容器'
    docker-compose down
    echo '2.删除代码目录'
    rm -rf $FILE
    echo '删除代码目录 正在停止容器 success'
    sleep 1
else
    echo '文件夹不存在'
    # shellcheck disable=SC2046
    docker stop $(docker ps -a  |grep $NAEM | awk -F " " '{print $1}')
    # shellcheck disable=SC2046
    docker rm $(docker ps -a  |grep $NAEM | awk -F " " '{print $1}')
    docker network rm gateway-network
    rm -rf $FILE
    echo '手动停止删除容器成功'
fi


echo '删除已废弃的 images'
  docker stop $(docker ps -a  |grep $NAEM | awk -F " " '{print $1}')
  docker rm $(docker ps -a  |grep $NAEM | awk -F " " '{print $1}')
  docker rmi $(docker images  |grep $NAEM | awk -F " " '{print $3}')
  docker rmi $(docker images  |grep none | awk -F " " '{print $3}')


cd $ROOT
git clone https://xiebbing%40126.com:bing940215@gitee.com/xie-bing/gateway.myui.git $FILE
# shellcheck disable=SC2164
cd  $FILE
git checkout master
echo '==============git clone success================'
sleep 1

echo '解压dist'
echo '检测unzip 是否安装'
sh install-package.sh unzip
#npm i
#npm run build
if [ -d $VOLUME ]
then
    echo 'Volume 文件夹存在'
    # shellcheck disable=SC2164
    rm -rf $VOLUME
    echo '删除Volume 文件夹  success'
    sleep 1
else
    echo '文件夹不存在'
    mkdir -p $VOLUME
    echo '创建Volume 文件夹 成功'
fi

mkdir dist

unzip -o dist.zip  -d ./dist
echo '==============解压dist success================'
sleep 1

API_URL="/api"

if [ $# -lt 1 ]; then
    echo '没有传参，接口地址将使用默认值 /api'
	sed -i "s|VUE_APP_API_BASEURL|$API_URL|g"  "$FILE/dist/config.js"
else
	API_URL=$1
	echo "有传参，参数为：$API_URL"
	sed -i "s|VUE_APP_API_BASEURL|$API_URL|g"  "$FILE/dist/config.js"

fi
cat "$FILE/dist/config.js"
docker-compose build

echo '==============build success================'

echo '-----------开始推送镜像-----------'
docker login -udeployer -pdeployer  $PUSHREMOTE
docker tag $NAME:latest  $PUSHREMOTE/$NAME:latest
docker  push $PUSHREMOTE/$NAME:latest

echo '==============push success================'


docker-compose up -d

echo '==============run success================'
